package com.stock_t.controller;

import com.stock_t.entity.FundFlowHistory;
import com.stock_t.service.FundFlowHistoryService;
import com.stock_t.page.TableDataInfo;
import com.stock_t.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资金流向历史数据Controller
 * 提供资金流向数据的RESTful API接口
 */
@Slf4j
@RestController
@RequestMapping("/fund/flow")
public class FundFlowHistoryController {

    @Autowired
    private FundFlowHistoryService fundFlowHistoryService;


    /**
     * 根据股票代码查询资金流向历史数据
     */
    @GetMapping("/history/{stockCode}")
    public Map<String, Object> getFundFlowHistory(@PathVariable("stockCode") String stockCode) {
        log.info("查询股票 {} 的资金流向历史数据", stockCode);
        
        List<FundFlowHistory> fundFlowList = fundFlowHistoryService.getFundFlowByStockCode(stockCode);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", fundFlowList);
        result.put("msg", "success");
        
        return result;
    }

    /**
     * 根据股票代码和日期范围查询资金流向数据
     * 如果startDate和endDate不传递，则查询全量数据
     */
    @GetMapping("/range/{stockCode}")
    public Map<String, Object> getFundFlowByDateRange(@PathVariable("stockCode") String stockCode,
                                                      @RequestParam(value = "startDate", required = false) String startDate,
                                                      @RequestParam(value = "endDate", required = false) String endDate) {
        
        List<FundFlowHistory> fundFlowList;
        
        // 如果日期参数为空，查询全量数据
        if (startDate == null || endDate == null) {
            log.info("查询股票 {} 的全量资金流向数据", stockCode);
            fundFlowList = fundFlowHistoryService.getFundFlowByStockCode(stockCode);
        } else {
            log.info("查询股票 {} 在 {} 到 {} 期间的资金流向数据", stockCode, startDate, endDate);
            try {
                LocalDate start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                fundFlowList = fundFlowHistoryService.getFundFlowByDateRange(stockCode, start, end);
            } catch (Exception e) {
                log.error("日期格式解析失败", e);
                Map<String, Object> result = new HashMap<>();
                result.put("code", 400);
                result.put("msg", "日期格式错误，请使用yyyy-MM-dd格式");
                return result;
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", fundFlowList);
        result.put("msg", "success");
        
        return result;
    }

    /**
     * 同步资金流向数据
     */
    @PostMapping("/sync")
    public Map<String, Object> syncFundFlowData() {
        log.info("开始同步全量股票的资金流向数据");
        
        boolean success = fundFlowHistoryService.syncFundFlowData();
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", success ? 200 : 500);
        result.put("msg", success ? "同步成功" : "同步失败");
        
        return result;
    }


    /**
     * 清理过期数据
     */
    @DeleteMapping("/clean")
    public Map<String, Object> cleanExpiredData(@RequestParam("daysToKeep") int daysToKeep) {
        log.info("开始清理 {} 天前的资金流向数据", daysToKeep);
        
        int deletedCount = fundFlowHistoryService.cleanExpiredData(daysToKeep);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", deletedCount);
        result.put("msg", "清理完成，共删除 " + deletedCount + " 条记录");
        
        return result;
    }
}